
const validate = require("validate.js")
const {StudentSInfon} = require("../models/StudentSInfon")
const moment = require("moment")
/**
 * 学生打卡统一处理
 * @param {*} limitTime 规定什么时间后打卡
 * @param {*} id 学生id
 * @param {Function} callback 回调函数
 */
exports.StudentRecords = async function(limitTime,id,callback){
    const current = moment.utc().local().format("YYYY-MM-DD HH:mm:ss") // 当前的时间
    if(limitTime){
        if(moment(current.split(" ")[1],"HH:mm:ss").diff(moment(limitTime,"HH:mm:ss"),"seconds") < 0){
            return {
                code: 401,
                err: "It's not time to clock in yet"
            }
        }
    }
    validate.validators.StudentExits = async function(value){
        const res = await StudentSInfon.findByPk(value);
       
        if(res){
            return
        }
        return "is not Exits"
    }
    // 验证规则
    const rule = {
        id:{
            presence: {
                allowEmpty:false
            },
            StudentExits: true
        }
    }
    try{
        
        await validate.async({id},rule)
        const res = await StudentSInfon.findByPk(id,{
            attributes:["checkInTime"]
        })
        const checkInTime = moment.utc(res.toJSON().checkInTime).local().format("YYYY-MM-DD HH:mm:ss")
        
        const time = moment(checkInTime.split(" ")[0],"YYYY-MM-DD").diff(moment(current.split(" ")[0],"YYYY-MM-DD"),"days")
        if(time === 0){
            throw "Cannot check-in on the day of check-in"
        }
        const reslut = await callback(current)
        
        return reslut
    }catch(err){
        throw err
    }
}